<template>
	 <ex-dialog v-model="visible" draggable :title="'导入资产编码'"
	:width=700 :contentHeight=250 :top=160>
		<template #default>
			<el-progress v-if="loading" :text-inside="true" :stroke-width="20" :percentage="percentage"/>
			<div v-loading="loading">
				<el-upload
					drag
					class="upload-demo" ref="upload" accept=".xls,.xlsx"
					action=""
					:on-change="upload"
					:show-file-list="false"
					:auto-upload="false"
					>
					<slot name="uploader">
						<el-icon class="el-icon--upload"><el-icon-upload-filled /></el-icon>
						<div class="el-upload__text">
							将文件拖到此处或 <em>点击选择文件上传</em>
						</div>
					</slot>
					<template #tip>
						<div class="el-upload__tip">
							<template v-if="tip">{{tip}}</template>
							<template v-else>请上传小于或等于 {{maxSize}}M 的 {{accept}} 格式文件</template>
							<el-link @click="downloadTemplate" target="_blank" type="primary" :underline="false">下载导入模板</el-link>
							<h5  style="color: red; font-size: 16px;">导入资产数量：{{assetCodes.length}}&nbsp;&nbsp;条</h5>
						</div>
					</template>
				</el-upload>
			</div>
		</template>
		<template #footer>
			<div style="flex: auto;text-align: center">
				<el-button plain type="primary" @click="save" :loading="loading">上传</el-button>
				<el-button plain type="info" @click="this.visible = false" :loading="loading">关 闭</el-button>
			</div>
		</template>
	</ex-dialog>
	<print-review ref="printReview"></print-review>
</template>

<script>
import scIconSelect from '@/components/scIconSelect/index.vue'
import ExRelTable from "@/components/exRelTable/index.vue";
import ExLabel from "@/components/exLabel/index.vue";
import ExFormItem from "@/components/exFormItem/index.vue";
import ExWidget from "@/components/exFormItem/widget.vue";
import * as xlsx from "xlsx";
import globalparam from "@/constant/model/globalparam";
import PrintReview from "@/views/asset/labelPrint/printReview.vue";
import exDialog from '@/components/exDialog';

export default {
	computed: {},
	emits: ['success'],
	components: {
		PrintReview,
		ExWidget,
		ExFormItem,
		ExLabel,
		ExRelTable,
		scIconSelect,
		exDialog
	},
	props: {
		menu: {
			type: Object, default: () => {
			}
		},
		accept: { type: String, default: ".xls, .xlsx" },
		maxSize: { type: Number, default: 10 },
		tip: { type: String, default: "" },
	},
	data() {
		return {
			visible: false,
			form: {},
			loading: false,
			assetCodes:[],
		}
	},
	watch: {},
	mounted() {

	},
	beforeMount() {
	},
	onLoad() {
	},
	methods: {
		//显示
		open(entity) {
			this.assetCodes=[];
			this.form = {};
			this.form = Object.assign({}, entity);
			this.oldForm = Object.assign({}, this.form);
			this.visible = true;
		},
		//保存
		async save() {
			try {
				if (this.assetCodes.length === 0) {
					this.$message.error('未读取到资产编码信息，请确认上传的文件是否符合要求')
					return;
				}
				this.loading = true;
				let data = {
					assetIds: this.assetCodes,
					taskId: this.form.taskId,
					documentId: this.form.id,
					createUser: this.form.createUser,
				};
				let rsp = await this.$API.asset.checkDetailApi.improt.post(data);
				if (rsp.code === 2000) {
					this.$emit('success');
					this.visible = false;
				}
			} finally  {
				this.loading = false;
			}
		},
		async downloadTemplate() {
			let minioServerUrl = await this.$TOOL.minioServerUrl();
			let paramValue = await this.$cache.data.loadGlobalParam(globalparam.checkPrintImportTemplate.paramCode);
			let templateUrl = null;
			if (paramValue) {
				let tempFiles = this.$TOOL.toObj(paramValue);
				if (tempFiles[0]) {
					templateUrl = minioServerUrl + tempFiles[0].realUrl;
				}
			}
			if (!templateUrl) {
				this.$message.error("未找到导入模板");
				return;
			}
			window.open(templateUrl);
		},
		upload (file, fileList) {
			const files = { 0: file.raw }// 取到File
			this.readExcel(files)
		},
		readExcel (files) { // 表格导入
			if (files.length <= 0) { // 如果没有文件名
				return false
			} else if (!/\.(xls|xlsx)$/.test(files[0].name.toLowerCase())) {
				this.$message.error('上传格式不正确，请上传xls或者xlsx格式')
				return false
			}

			const fileReader = new FileReader()
			fileReader.onload = (files) => {
				this.assetCodes=[];
				try {
					const data = files.target.result
					const workbook = xlsx.read(data, {
						type: 'binary'
					})
					const wsname = workbook.SheetNames[0]// 取第一张表
					const ws = xlsx.utils.sheet_to_json(workbook.Sheets[wsname])// 生成json表格内容
					// 重写数据
					this.$refs.upload.value = ''
					if(ws.length>0){
						ws.forEach(row=>{
							if(row['资产编码']){
								this.assetCodes.push(row['资产编码'].replace(/\s/g,""));
							}
						})
					}
					this.$message.success("导入的文件中包含了"+this.assetCodes.length+"条数据");
				} catch (e) {
					return false
				}
			}
			fileReader.readAsBinaryString(files[0])
		},

	}
}
</script>

<style scoped>
h2 {
	font-size: 17px;
	color: #3c4a54;
	padding: 0 0 30px 0;
}

[data-theme="dark"] h2 {
	color: #fff;
}
</style>
